<template>
    <h1>新增套餐</h1>
    <el-button @click="router.push('/taocan')" type="primary">&lt;返回</el-button>
  
    <div class="content">
    <div class="row"> <span class="font">套餐名称:</span><el-input class="dish" v-model="name"></el-input><br></div>
    <div  class="row"><span class="font"> 套餐分类:</span>
      <el-select v-model="catego" placeholder="选择分类">
         <el-option v-for="(item,index) in category" :lable="item" 
         :key="index" :value="item" ></el-option>
      </el-select>
      
      <br></div> 
    <div  class="row"> <span class="font">套餐价格:</span><el-input class="dish" v-model="totalPrice"
      type="number"></el-input></div> 
    </div>
   
   <!-- 套餐菜品 -->
   <div class="kouwei">
    <div class="kouwei-txt">套餐菜品:</div>
      
    <div class="kouwei-div">
      <el-button type="primary" @click="addVisable = true">添加菜品</el-button>
 

        <el-table :data="tableData" stripe style="width: 100%;height: 200px;" border>
            <el-table-column prop="dishname" label="菜品名称" width="180" />
            <el-table-column prop="price" label="原价" width="180" />
            <el-table-column prop="number" label="份数">
                <template #default="scope">
                    <el-input-number v-model="scope.row.number" :min="1" :max="99" @change="handleChange" />
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template #default="scope">
                 <a type="primary" @click="deleteDish(scope.$index,scope.row)" href="javascript:;">删除</a>
                </template>
            </el-table-column>
        </el-table>


    </div>
    

   </div>




<!-- 图片上传 -->
<div class="imgarea">
  <div>套餐图片</div>
  <el-upload
        class="avatar-uploader"
        :action="taocanImgUploadUrl"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
      >
        <img v-if="taocanImgDoUrl" :src="taocanImgDoUrl" class="avatar" style="width: 240px;height: 200px;margin-left: 200px;" />
        <el-icon v-else class="avatar-uploader-icon" style="width:240px;height: 200px;margin-left: 200px;
        border: 1px solid black;"><Plus /></el-icon>
      </el-upload>
   <div class="img-txt">
     <div>图片大小不超过2M</div>
     <div>仅能上传 PNG JPEG JPG类型图片</div>
   </div>

 </div>

  <!-- 状态选择 -->
  <div style="margin-top: 20px;">售卖状态</div>
<el-switch
    v-model="statusFlag"
    class="ml-2"
    style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949;
    margin-left: 100px;"
  />

<!-- 套餐描述 -->
<div class="desc">
  <div class="desc-title">套餐描述:</div>
  <div>
    <el-input
    style="width: 900px;margin-left: 100px;"
    v-model="description"
    :autosize="{ minRows: 4, maxRows: 6 }"
    type="textarea"
    placeholder="请输入套餐描述..."
  />
  </div>
</div>
<div class="submit">
  <el-button type="primary" class="sub" @click="addTaocan">保存</el-button>
<el-button  type="primary"  class="sub" @click="addAgain">保存并继续添加</el-button>
<el-button  type="primary"  class="sub" @click="resetAgain">重置</el-button>
</div>


<!-- 添加菜品对话框 -->
<el-dialog
     v-model="addVisable"
     title="添加菜品"
     width="70%"
     class="adddish"
   >
<!-- 搜索菜品 -->
  <el-input placeholder="请输入菜品名称" class="addinput"  @keyup.enter="search"
  v-model="searchName"></el-input>

  <!-- 双列列表 -->

  <li v-for="(item,index) in dishgate" :key="index" class="dishcate" 
   @click="getDishByCateId(index)" :id="'cate'+index" 
   :style="{ backgroundColor: colorIndex === index ? '#dbd6d9' : '#fcf7fa' }">
   <label> {{ item }}</label>
  </li>
 

  <el-table :data="dish" stripe style="width: 38%;height: 200px;" class="dishs" border 
   ref="multipleTableRef" @selection-change="handleSelectionChange" >
     
     <el-table-column type="selection" width="55" />
    <el-table-column prop="name" label="名称" width="110" />
    <el-table-column prop="status"  label="状态" width="110" />
    <el-table-column prop="price" label="价格" width="110"/>
  </el-table>

  
  <div class="right">
    <div class="right-title">已选菜品(1)</div>
    <li v-for="(item,index) in dishes" :key="index" class="right-dish">
     <div class="right-name">{{ item.name }}</div>
     <div class="right-price">{{ item.price }}</div>
     <el-icon class="right-icon" size="20" @click="deldish(index)"><CircleClose /></el-icon>
    </li>
  </div>
 
  <div class="but">
      <el-button type="primary" @click="addDish">添加</el-button>
      <el-button  type="primary" @click="toAddDishes">确定</el-button>
      <el-button  type="primary" @click="reset">取消</el-button>
  </div>


</el-dialog>


 <!-- 删除对话框 -->
 <el-dialog
     v-model="delVisable"
     title="删除菜品"
     width="30%"
     align-center
   >
     <span>你确定要删除该菜品吗?</span>
     <template #footer>
       <span class="dialog-footer">
         <el-button @click="delVisable = false">取消</el-button>
         <el-button type="primary" @click="deleteOne">
           确定
         </el-button>
       </span>
     </template>
   </el-dialog>

<!-- 图片展示对话框
<el-dialog v-model="dialogVisible">
    <img w-full :src="dialogImageUrl" alt="Preview Image" />
</el-dialog> -->


</template>


<script setup lang="ts">
import { useRouter } from 'vue-router';
import { computed, ref } from 'vue';
import { ElInput, POPPER_CONTENT_INJECTION_KEY, UploadProps, alertProps } from 'element-plus';
import { onMounted } from 'vue';
import {ElMessage}from 'element-plus'
import categoryApi from '@/api/category';
import { taocanImgUrl,taocanImgUploadUrl } from '@/config/imgconfig';
import dishApi from '@/api/dish';
import taocanApi from '@/api/taocan';
import imgApi from '@/api/imgApi'
const router = useRouter()

//套餐的数据

const name = ref('')
const price = ref()
const catego = ref('')
const description = ref('')
//默认的数量
const num = ref(1)
//售卖状态
const statusFlag = ref(true)

//计算属性用来统计价格
//总价
const totalPrice = computed(()=>{
  
      var price =0;
      tableData.value.forEach(it=>{
          console.log("循环...");
          var itPrice = it.price * it.number;
          price += itPrice 
      })
      //console.log("价格是:"+price);
      return price;
   
  })









onMounted(()=>{
  //获取套餐数据
  getTaocanCate()
    //先把菜品分类给查出来，防止每次点击都查
    getDishCate()
})

//菜品数据

const tableData = ref([
    // {
    //     dishname:'鱼香肉丝',
    //     price:12.5,
    //     number:1
    // },
])

//套餐分类名称集合
const category = ref([])
//套餐分类详细集合，主要是为了获取id
const taocanGory = ref([])



//查询套餐分类
async function getTaocanCate(){
  const res = await categoryApi.getTaocanCate()
  if(res.code===200){
      res.data.forEach((item:{name:string})=>{
      category.value.push(item.name)
  })
  }
  
}


//菜品分类
const dishgate = ref([])
//菜品分类详情集合，为了获取菜品分类id
const dishCates = ref([])

//每一个菜品分类所包含的菜品
const dish = ref([
  // {name:'鱼香肉丝',status:'在售',price:'40'},
  // {name:'红烧肉',status:'在售',price:'20'},
  // {name:'回锅肉',status:'在售',price:'10'}
])

//查询菜品分类
async function getDishCate(){
  const res = await categoryApi.getDishCate()
  if(res.code===200){
     res.data.forEach((item: { name: string; })=>{
     dishgate.value.push(item.name)
     dishCates.value.push(item)
  })
  }
 
}
//用来保存点击的索引，换颜色用
const colorIndex = ref(-1)
//根据菜品的分类id查询菜品
//index 是菜品名称数组的索引，它和菜品详情数组的索引相同，
//可以利用他的索引找到对应菜品的分类id，然后去查询菜品
const getDishByCateId=async (idx:any)=>{
    //将搜索框里的字符串清空
    searchName.value = ''
    colorIndex.value = idx
    var dishCateId = dishCates.value[idx].id
    const res = await dishApi.getDishesByCateId(dishCateId);
    if(res.code===200){
       dish.value = res.data
    }else{
       ElMessage({"message":res.data,"type":"error"})
    }
    
}
//搜索菜品时的名称
const searchName = ref('')
//搜索菜品根据名称
const search=async ()=>{
  if(searchName.value==''||searchName.value==undefined){
    return;
  }
  //应该把分类那个黑色的选中状态去掉
  colorIndex.value = -1
  const res = await dishApi.getDishByName(1,100,searchName.value)
  if(res.code===200){
    dish.value = res.data.list
  }
}

 //多选功能
 const multipleTableRef = ref<InstanceType<typeof ElTable>>()
 //多选数组
 const multipleSelection = ref<[]>([])
 const toggleSelection = (rows?:[]) => {
   if (rows) {
     rows.forEach((row) => {
       multipleTableRef.value!.toggleRowSelection(row, undefined)
     })
   } else {
     multipleTableRef.value!.clearSelection()
   }
 }
 const handleSelectionChange = (val:[]) => {
     multipleSelection.value = val
 }

//从已选择的备选框中删除菜品
const deldish=(index:any)=>{
   dishes.value.splice(index,1)
}
//取消添加，重置
const reset=()=>{
   addVisable.value = false;
   dishes.value=[]
   multipleSelection.value=[]
}
//确定要添加菜品了
const toAddDishes=()=>{
  if(dishes.value.length==0){
    ElMessage({"message":"请添加菜品","type":"warning"})
    return;
  }
  //还是的先判断是否已经选过了
   var flag = true;
   tableData.value.forEach(it=>{
     dishes.value.forEach(item=>{
        if(it.dishname==item.name){
           flag = false
           ElMessage({"message":it.dishname+"已经选过了！","type":"warning"})
           return 
        }
     })
   })
   if(flag==true){
        //没有重复，可以添加
        dishes.value.forEach(it=>{
         tableData.value.push({dishId:it.id,dishname:it.name,price:it.price,number:1})
       })
        //添加完之后清空选择框
        dishes.value = []
        addVisable.value = false;
      }

   
}

//数量变化
const handleChange = (value: number) => {
  console.log(value)
}



//删除对话框的标志
const delVisable = ref(false)
const delIndex = ref(0)
//删除菜品按钮
const deleteDish=(index:number,row:any)=>{
    delVisable.value = true
    delIndex.value = index
}
//删除一行
const deleteOne = (index:number)=>{
  //将table中的数据删除一行
   tableData.value.splice(delIndex.value,1)
   delVisable.value = false
   deleteMsg()
}




const deleteMsg = () => {ElMessage({ message: '已删除该菜品',type: 'success', })}


//添加菜品对话框是否可见
const addVisable = ref(false)

//向备选框中添加菜品
const addDish = () =>{
    if(multipleSelection.value.length==0){
      ElMessage({"message":"所选菜品不能为空","type":"warning"})
      return ;
      
    }
   // console.log(multipleSelection.value);
   var flag = true;
   
      dishes.value.forEach(it=>{
       multipleSelection.value.forEach(item=>{
          if(it.name==item.name){
            ElMessage({"message":it.name+"已经选过了!","type":"warning"})
            flag = false;
            return;
            console.log("hhhh");
          }
       })
    })
      if(flag==true){
        //没有重复，可以添加
       multipleSelection.value.forEach(it=>{
         dishes.value.push(it)
       })
        //添加完之后清空多选框
       multipleSelection.value = []
      }
      
    
}

//已选择的菜品
const dishes = ref([
    // {name:'西红柿鸡蛋',price:12.5},
    // {name:'红烧肉',price:19.0}
])

//套餐图片的名称
const taocanImgName = ref('')
//套餐图片下载地址
const taocanImgDoUrl = ref('')

//图片上传
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
 if (rawFile.type !== 'image/jpeg') {
   ElMessage.error('图片格式必须是jpg')
   return false
 } else if (rawFile.size / 1024 / 1024 > 2) {
   ElMessage.error('图片大小不能大于2MB')
   return false
 }
 return true
}
//图片上传成功之后的操作
const handleAvatarSuccess: UploadProps['onSuccess'] = (
 response,
 uploadFile
) => {
  taocanImgName.value = response.data
  taocanImgDoUrl.value= URL.createObjectURL(uploadFile.raw!)
}

//新增套餐了
const addTaocan=async ()=>{
   //检查名称是否为空
  if(name.value===''||name.value===null || name.value===undefined){
      ElMessage({"message":"套餐名称不能为空","type":"warning"})
      return
    } 
    if(catego.value===''||catego.value===null || catego.value===undefined){
      ElMessage({"message":"分类不能为空","type":"warning"})
      return;
    }
    
    if(totalPrice.value==0  ){
      ElMessage({"message":"价格不能为0","type":"warning"})
      return
    }
    if(tableData.value.length==0){
      ElMessage({"message":"菜品不能为空","type":"warning"})
      return
    }
    if(taocanImgName.value===''||taocanImgName.value===null||taocanImgName.value===undefined){
      ElMessage({"message":"图片不能为空","type":"warning"})
      return
    } 
    //检验通过，可以添加
    //构造套餐对象
    const taocanVo = {
       name:name.value,
       category:catego.value,
       totalPirce:totalPrice.value,
       img:taocanImgName.value,
       description:description.value,
       //菜品组合
       dishes:tableData.value,
       //售卖状态
       status:statusFlag.value==true?"在售":"停售"
    }
    console.log(taocanVo);

    //添加套餐
    const res = await taocanApi.insertTaocan(taocanVo);
    if(res.code===200){
      ElMessage({"message":res.data,"type":"success"})
      addAgainFlag.value = true;
    }else{
      ElMessage({"message":res.data,"type":"error"})
      addAgainFlag.value = false
    }

    
}



//重置所有的东西
const resetAgain=async ()=>{
   name.value = ''
   tableData.value = []
   catego.value = ''
   description.value =''
   statusFlag.value = true
   //将套餐图片删除
   if(taocanImgName.value===''||taocanImgName.value===undefined){
     taocanImgName.value = ''
   }else{
      const res = await imgApi.deleteTaocanImg(taocanImgName.value)
     if(res.code!==200){
       ElMessage({"message":res.data,"type":"error"})
     }
   }
   
   taocanImgName.value = ''
   taocanImgDoUrl.value = ''

   
}

//保存继续添加flag值(false表示重置，true则不重置)
const addAgainFlag = ref(false)


//保存并继续添加
const addAgain=()=>{
  //先添加
   addTaocan()
  if(addAgainFlag.value==true){
    //在重置
    resetAgain()
  }
  

}



</script>


<style scoped lang="less">

li{
    list-style: none;
}
a{
    text-decoration: none;
    color: black;
}
a:hover{
    color: rgb(95, 93, 91);
}

.content{
  
  margin-left: 100px;
}
.dish{
    width: 300px;
}

.row{
    margin-top: 20px;
  
 .font{
    margin-right: 20px;
 }
}
.kouwei{
    margin-top: 50px;

   .kouwei-txt{
      margin-left: 30px;
   }
   .kouwei-div{
      width: 900px;
      height: 150px;
      border: 1px solid black;
      border-bottom: none;
      margin-left: 150px;
     .kouwei-two{
      margin-top: 10px;
      margin-left: 10px;
   }
   .select{
     float: left;
     margin-left: 10px;
   }
   .tag{
     float: left;
     width: 500px;
     height: 33px;
     background-color: white;
     margin-left: 20px;
     margin-bottom: 5px;
     padding-top: 5px;
     padding-left: 10px;
     .el-tag{
        margin-right: 10px;
     }

   }
   .del{
       display: block;
       margin-bottom: 20px;
        
      
   }
}
}

//标签输入框
.ml-1{
  width: 60px;
}

//添加口味按钮
.addbutton{
  margin-top: 10px;
  margin-right: 350px;
  margin-left: 20px;
}

//图片区域
.imgarea{
   
  margin-top: 100px;
  
 .upload{
  margin-left: 150px;
 }
 .img-txt{
   position: absolute;
   margin-left: 350px;
   bottom: 1px;
 }
}

//保存按钮
.submit{
   margin-top: 20px;
   margin-left: 400px;
   margin-bottom: 100px;
   .sub{
     margin-bottom: 30px;
   }
}

//添加菜品对话框
.adddish{
    height: 500px;
    .left{
        float: left;
        width:200px;
        height: 200px;
        background-color: aqua;
    }
    // .right{
    //     float: left;
    //     width:200px;
    //     height: 200px;
    //     background-color: aquamarine;
    // }
    // .right{
    //     background-color: antiquewhite;
    //     width: 200px;
    //     height: 200px;
       
    // }
    .addinput{
        width: 500px;
    }
}

.el-dialog__body{
  height: 400px;
}



.dishcate{
  width: 100px;
  height: 30px;
  position: relative;
  top:30px;
  
  margin-bottom: 10px;
  background-color: rgb(255, 255, 255);
  text-align: center;
  line-height: 30px;
}
.dishcate:hover{
   background-color: rgb(213, 211, 208);
}
.dishs{
  width:100px;
  height:30px;
  bottom: 60px;
  position: absolute;
  left: 120px;

}

.right{
  position: absolute;
  left: 600px;
  bottom: 100px;
  .right-title{
    width:400px;
    height: 30px;
    background-color: rgb(175, 171, 171);
    line-height: 30px;
    text-align: center;
  }
  .right-dish{
    width:400px;
    height: 60px;
    border-bottom: 1px solid rgb(88, 84, 84);
    border-left: 1px solid rgb(88, 84, 84);
    border-right: 1px solid rgb(88, 84, 84);
  }
  .right-name{
    margin-left: 10px;
    margin-bottom: 10px;
    margin-top: 5px;
  }
  .right-price{
    margin-left: 10px;
  }
  .right-icon{
    margin-left: 350px;
    position: relative;
    bottom: 30px;
  }
  .right-icon:hover{
    color: black;
  }
}

 .but{
   position: absolute;
   left:400px;
   top: 400px;
   height: 200px;
 }

</style>